package com.ebt.m.proposal_v2.ui;


import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.TextView;

import com.ebt.m.R;
import com.ebt.m.customer.util.DisplayUtil;
import com.ebt.m.event.ProposalListTabCheckedEvent;
import com.ebt.m.fragment.BaseFragment;
import com.ebt.m.jpush.JPushResult;
import com.ebt.m.jpush.JPushUtil;
import com.ebt.m.proposal_v2.utils.ProposalUtils;
import com.ebt.m.proposal_v2.utils.Utils;
import com.ebt.m.utils.TalkingDataUtil;
import com.ebt.m.view.ProposalListView;
import com.ebt.m.widget.SlidingTabLayout;
import com.jakewharton.rxbinding2.view.RxView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.concurrent.TimeUnit;

/**
 * Created by Rick.Wang on 2017/5/31.
 */
public class FragmentProposalList extends BaseFragment implements JPushUtil.OnJPushReceivedListener {
    public static final String SHOW_BACK = "SHOW_BACK";
    private FrameLayout mCancel;
    private TextView mNew;
    private ViewPager mVpContent;
    private SlidingTabLayout mSlidingTabLayout;
    private String[] titles;

    public static FragmentProposalList newInstance(boolean showBack) {
        FragmentProposalList frg = new FragmentProposalList();
        Bundle bundle = new Bundle();
        bundle.putBoolean(SHOW_BACK, showBack);
        frg.setArguments(bundle);
        return frg;
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        titles = getResources().getStringArray(R.array.proposal_list_titles);
        EventBus.getDefault().register(this);
        JPushUtil.registerJPushReceivedListener(this);
    }

    @Override
    public void onDetach() {
        super.onDetach();
        EventBus.getDefault().unregister(this);
        JPushUtil.unregisterJPushReceivedListener(this);
    }

    @Override
    public void onCreateView(Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.view_proposal_list, null);
        setContentView(view);
        initView();
    }

    public void initView() {
        mNew = (TextView) findViewById(R.id.btn_new);
        mCancel = (FrameLayout) findViewById(R.id.btn_cancel);
        if (getArguments() != null && getArguments().getBoolean(SHOW_BACK)) {
            mCancel.setVisibility(View.VISIBLE);
        } else {
            mCancel.setVisibility(View.INVISIBLE);
        }

        RxView.clicks(mNew)
                .throttleFirst(500, TimeUnit.MILLISECONDS)
                .subscribe(aVoid -> {
                    gotoNewProposal();
                    TalkingDataUtil.onEventWithAgentId(TalkingDataUtil.TYPE_PROPOSAL_LIST_NEW_V270);
                });

        RxView.clicks(mCancel)
                .throttleFirst(500, TimeUnit.MILLISECONDS)
                .subscribe(aVoid -> {
                    ((Activity) getContext()).finish();
                });

        mVpContent = (ViewPager) findViewById(R.id.vp_content);
        mSlidingTabLayout = (SlidingTabLayout) findViewById(R.id.sliding_tab_layout);
        mVpContent.setAdapter(new ProposalPageAdapter());
        mSlidingTabLayout.setDistributeEvenly(true);
        mSlidingTabLayout.setDistributeEvenlyWhenWidthNotFull(true, DisplayUtil.getScreenWidth(getContext()));
        mSlidingTabLayout.setViewPager(mVpContent);
        mVpContent.setOffscreenPageLimit(5);
        mVpContent.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                ProposalListTabCheckedEvent event = new ProposalListTabCheckedEvent();
                event.position = position;
                EventBus.getDefault().post(event);
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        mVpContent.post(() -> {
            ProposalListTabCheckedEvent event = new ProposalListTabCheckedEvent();
            event.position = 0;
            EventBus.getDefault().post(event);
        });
    }


    private void gotoNewProposal() {
        ProposalUtils.gotoMakeNewProposal(getContext());
    }

    @Override
    public void onJPushReceived(JPushResult result) {
        if (result != null && result.message != null) {
            if (("BusinessOpportunity").equals(result.message.topic) && ("ProposalView").equals(result.message.action)) {
                if (mVpContent.getCurrentItem() == 0 ||
                        mVpContent.getCurrentItem() == 3 ||
                        mVpContent.getCurrentItem() == 4) { // 当前处于全部, 已发送，被查看时刷新
                    postRefresh(mVpContent.getCurrentItem());
                }
            }
        }
    }

    private class ProposalPageAdapter extends PagerAdapter {

        @Override
        public int getCount() {
            return 5;
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView((View) object);
        }

        @Override
        public void destroyItem(View container, int position, Object object) {
            super.destroyItem(container, position, object);
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            ProposalListView listView = new ProposalListView(getContext(), position);
            container.addView(listView);
            return listView;
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return titles[position];
        }
    }

    @Subscribe
    public void onTabChangedEvent(ProposalListTabCheckedEvent event) {
        if (event.position == -1) {
            Utils.print("draft", ">>fragment -> " + event);
            postRefresh(mVpContent.getCurrentItem());
        }
    }

    /**
     * 发送刷新数据信号
     *
     * @param position
     */
    private void postRefresh(int position) {
        mVpContent.postDelayed(() -> {
            EventBus.getDefault().post(new ProposalListTabCheckedEvent(position));
        }, 500);
    }
}
